package gzhaoku.com.machinemain.jssdk;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;
import android.widget.VideoView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.sunmi.printerhelper.utils.AidlUtil;


import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;

import cz.msebera.android.httpclient.Header;
import gzhaoku.com.common.Logger;
import gzhaoku.com.common.ui.components.XWebView;
import gzhaoku.com.common.util.Api;
import woyou.aidlservice.jiuiv5.ICallback;
import woyou.aidlservice.jiuiv5.IWoyouService;

public class SDK {

    static boolean isSubviewHidden =  false;

    Logger log = Logger.getLog(this);

    Activity context;
    XWebView webView;
    XWebView subWebView;

    String lastInvokeId;

    SDKListener listener;


    public SDK(Activity context, XWebView webView, XWebView subWebView){
        this.context = context;
        this.webView = webView;
        this.subWebView = subWebView;
    }

    public void setListener(SDKListener l){
        this.listener = l;
    }

    @JavascriptInterface
    public void testNetwork(final String invokeId, String encodeParamJson) {
        log.i("js invoke testNetwork()");
        JSONObject params = params(encodeParamJson);
        Api.testNetwork(new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, org.json.JSONObject response) {
                if(response.has("timestamp")){
                    JSONObject params = new JSONObject();
                    try {
                        params.put("timestamp", response.getInt("timestamp") * 1000);
                        doSuccCallback(invokeId, params);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }else{
                    doFailCallback(invokeId, "服务器异常，5秒后重试...");
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, org.json.JSONObject errorResponse) {
                doFailCallback(invokeId, "无法连接服务器，5秒后重试...");
            }
        });

    }

    @JavascriptInterface
    public void print(final String invokeId, String encodeParamJson) {
        log.i("js invoke getSetting()");
        JSONObject params = params(encodeParamJson);

        com.alibaba.fastjson.JSONArray array = params.getJSONArray("data");
        if(array.size() > 0){
                        IWoyouService service = AidlUtil.getInstance().getWoyouService();


            try {

                service.enterPrinterBuffer(true);

                for (int i = 0; i < array.size(); i++) {
                    JSONObject printItem = array.getJSONObject(i);

                    int type = printItem.getInteger("type");


                    Integer align = printItem.getInteger("align");
                    if(align != null){
                        service.setAlignment(align, null);
                    }

                    Integer fontSize = printItem.getInteger("fontSize");
                    if(fontSize != null){
                        service.setFontSize(fontSize, null);
                    }

                    switch (type){
                        case 1: //文本
                            String text = printItem.getString("data");
                            service.printText(text, null);
                            service.lineWrap(1,  null);
                            break;
                        case 2: //二维码
                            String url = printItem.getString("data");
                            Integer qgap = printItem.getInteger("gap");
                            if(qgap == null){
                                qgap = 1;
                            }
                            service.lineWrap(qgap,  null);
                            service.printQRCode(url, fontSize, 1, null);
                            service.lineWrap(qgap,  null);
                            break;
                        case 3: //表格
                            com.alibaba.fastjson.JSONArray items = printItem.getJSONArray("data");
                            int tableSize = items.size();
                            String[] texts = new String[tableSize];
                            int[] widths = new int[tableSize];
                            int[] aligns = new int[tableSize];


                            for (int j = 0; j < tableSize; j++) {
                                JSONObject item = items.getJSONObject(j);
                                texts[j] = item.getString("text");
                                widths[j] = item.getInteger("width");
                                aligns[j] = item.getInteger("align");
                            }

                            service.printColumnsString(texts, widths, aligns, null);
                            service.lineWrap(1,  null);
                            break;
                        case 4: //走行
                            Integer line = printItem.getInteger("data");
                            service.lineWrap(line,  null);
                            break;
                        case 5: //表格
                            /*
                            * {
                            *   type: 5,
                            *   gap: 2
                            *   width: [40, 60],
                            *   fontSize: 24,
                            *   data: [
                            *       ["订单号","123132"],
                            *       ["订单号","123132"],
                            *       ["订单号","123132"],
                            *       ["订单号","123132"]
                            *   ]
                            * }
                            * */

                            com.alibaba.fastjson.JSONArray ditems = printItem.getJSONArray("data");
                            com.alibaba.fastjson.JSONArray dwidths = printItem.getJSONArray("width");
                            Integer gap = printItem.getInteger("gap");
                            if(gap == null){
                                gap = 1;
                            }

                            for (int j = 0; j < ditems.size(); j++) {
                                com.alibaba.fastjson.JSONArray item = ditems.getJSONArray(j);

                                service.printColumnsString(new String[]{
                                            item.getString(0) + StringUtils.repeat(' ', gap),item.getString(1)
                                        }
                                        , new int[]{
                                            dwidths.getInteger(0), dwidths.getInteger(1)
                                        }, new int[]{
                                            2, 0
                                        }, null);

                            }



                            service.lineWrap(1,  null);
                            break;
                    }

                }



//                service.commitPrinterBuffer();
                service.exitPrinterBufferWithCallback(true, new ICallback.Stub(){


                    @Override
                    public void onRunResult(boolean isSuccess) throws RemoteException {

                    }

                    @Override
                    public void onReturnString(String result) throws RemoteException {
                        Log.i("sunmi", "onReturnString:"+result);
                    }

                    @Override
                    public void onRaiseException(int code, String msg) throws RemoteException {
                        Log.i("sunmi", "onRaiseException:"+code+","+msg);
                    }

                    @Override
                    public void onPrintResult(int code, String msg) throws RemoteException {
                        if(code == 0){//打印成功
                            doSuccCallback(invokeId, "OK");
                        }else{
                            doFailCallback(invokeId, msg);
                        }
                    }
                });
            } catch (RemoteException e) {
                Log.e("sunmi", "Error in printing!", e);
            }
        }
    }

    @JavascriptInterface
    public void scanQr(final String invokeId, String encodeParamJson) {
        log.i("js invoke getSetting()");
        JSONObject params = params(encodeParamJson);

//        com.alibaba.fastjson.JSONArray array = params.getJSONArray("data");

        Intent intent = new Intent("com.summi.scan");
        intent.setPackage("com.sunmi.sunmiqrcodescanner");

        intent.putExtra("CURRENT_PPI", 0X0003);
        intent.putExtra("PLAY_SOUND", true);
        intent.putExtra("PLAY_VIBRATE", true);
        intent.putExtra("IDENTIFY_INVERSE_QR_CODE", true);
        intent.putExtra("IDENTIFY_MORE_CODE", true);
        intent.putExtra("IS_SHOW_SETTING", true);
        intent.putExtra("IS_SHOW_ALBUM", true);


        final int START_SCAN = 0x0001;

        lastInvokeId = invokeId;

        this.context.startActivityForResult(intent, START_SCAN);
    }

    @JavascriptInterface
    public void onPageReady(final String invokeId, String encodeParamJson) {
        log.i("js invoke getSetting()");
        JSONObject params = params(encodeParamJson);
        String url = params.getString("url");
        if(listener != null){
            try{
                listener.onPageReady(url);
                doSuccCallback(invokeId, url);
            }catch (Exception e){
                doFailCallback(invokeId, e.toString());
            }

        }
    }

    /**
     * When Activity received scan callback , this function will boardcast to web.
     * @param url
     */
    public void doScanQr(String url){

        if(StringUtils.isNoneEmpty(url)){//扫码成功
            doSuccCallback(lastInvokeId, url);
        }else{
            doFailCallback(lastInvokeId, "FAIL");
        }
    }



    private JSONObject params(String encodeParams){

        String paramJson = new String(Base64.decode(encodeParams, Base64.DEFAULT));
        JSONObject params = JSON.parseObject(paramJson);
        return params;
    }

    protected void doSuccCallback(final String invokeId, String data){
        final JSONObject result = new JSONObject();
        result.put("code", 0);
        result.put("data", data);
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl(String.format("javascript:window._invoke['%s'].success('%s');",  invokeId, Base64.encodeToString(result.toJSONString().getBytes(), Base64.DEFAULT)));
            }
        });
    }

    protected void doSuccCallback(final String invokeId, final WebView webViewClient, String data){
        final JSONObject result = new JSONObject();
        result.put("code", 0);
        result.put("data", data);
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webViewClient.loadUrl(String.format("javascript:window._invoke['%s'].success('%s');",  invokeId, Base64.encodeToString(result.toJSONString().getBytes(), Base64.DEFAULT)));
            }
        });
    }

    protected void doSuccCallback(final String invokeId, final WebView webViewClient, JSONObject params){
        final JSONObject result = new JSONObject();
        result.put("code", 0);
        result.put("data", params);
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webViewClient.loadUrl(String.format("javascript:window._invoke['%s'].success('%s');",  invokeId, Base64.encodeToString(result.toJSONString().getBytes(), Base64.DEFAULT)));
            }
        });
    }

    protected void doSuccCallback(final String invokeId, JSONObject params){
        final JSONObject result = new JSONObject();
        result.put("code", 0);
        result.put("data", params);
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl(String.format("javascript:window._invoke['%s'].success('%s');",  invokeId, Base64.encodeToString(result.toJSONString().getBytes(), Base64.DEFAULT)));
            }
        });
    }

    protected void doNotify(JSONObject params){
        final JSONObject result = new JSONObject();
        result.put("code", 0);
        result.put("data", params);
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                subWebView.loadUrl(String.format("javascript:window._notify('%s');", Base64.encodeToString(result.toJSONString().getBytes(), Base64.DEFAULT)));
            }
        });
    }

    protected void doFailCallback(final String invokeId, String message){
        final JSONObject result = new JSONObject();
        result.put("code", 1);
        result.put("message", message);
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl(String.format("javascript:window._invoke['%s'].fail('%s');",  invokeId, Base64.encodeToString(result.toJSONString().getBytes(), Base64.DEFAULT)));
            }
        });
    }

    protected void doFailCallback(final String invokeId, final WebView webViewClient, String message){
        final JSONObject result = new JSONObject();
        result.put("code", 1);
        result.put("message", message);
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webViewClient.loadUrl(String.format("javascript:window._invoke['%s'].fail('%s');",  invokeId, Base64.encodeToString(result.toJSONString().getBytes(), Base64.DEFAULT)));
            }
        });
    }


}
